<template>
	<!-- 司机 未完成 和 已完成 详情，未完成前可以修改， 已完成不可以修改 -->
	<view class="container">
		<u-alert-tips v-if="cache.dataChangeMsgs && cache.dataChangeMsgs.length" type="warning" title="" :description="descriptionGet()"></u-alert-tips>
		<view class="centerItem">
			<uni-section type="line" class="mb-5" title="基本信息"></uni-section>
			<view class="centerItemBody">
				<view :class="{ centerItemBodyList: true, isId: key == 'id' }" v-for="(item, key) of tableLabel">
					<text class="label">{{ item }}：</text>
					<!-- vehicleState: '车辆状态', -->
					<text class="value" v-if="key == 'vehicleState'">
						{{ vehicleStateValue[formData['vehicleState']] }}
					</text>
					<text class="value" v-else>{{ formData[key] || '--' }}</text>
				</view>
			</view>

			<view class="redText">
				<text>注:请正确填写装卸数据，榜单拍照要清晰，以免影响运费结算。</text>
			</view>
		</view>
		<!-- 已到厂可以修改 装车榜单 -->
		<view class="centerItem" v-if="[2, 4].includes(+formData.vehicleState)">
			<uni-section type="line" class="mb-10" title="装车信息">
				<template v-slot:right>
					<text v-if="handStatus.editLoading" @click="close(0)">保存</text>
					<text v-else @click="open(0)">编辑</text>
				</template>
			</uni-section>
			<!-- 装车信息form -->
			<uni-forms :modelValue="formData">
				<uni-forms-item label-width="180rpx" required name="loadingDate" label="装车日期">
					<uni-datetime-picker :disabled="!handStatus.editLoading" type="date" v-model="formData.loadingDate" />
				</uni-forms-item>
				<uni-forms-item label-width="180rpx" required label="实装吨位" name="loadingTonnage">
					<uni-easyinput :disabled="!handStatus.editLoading" type="digit" v-model="formData.loadingTonnage" placeholder="请填写" />
				</uni-forms-item>
				<uni-forms-item label-width="180rpx" required label="装车榜单" name="bd">
					<u-upload
						v-if="handStatus.editLoading"
						:key="getloadList.length + 'load'"
						width="110"
						height="110"
						ref="rupload"
						:max-count="1"
						:max-size="15 * 1024 * 1024"
						upload-text="上传"
						@on-oversize="() => overSize('装车榜单')"
						@on-success="(data) => onSuccess(data, 'loading')"
						@on-remove="(idx) => onRemove(idx, 'loading')"
						@on-error="onError"
						@on-choose-complete="onChooseComplete"
						:header="header"
						:file-list="getloadList"
						:action="baseFilesURL"
					></u-upload>
					<u-image v-else width="100rpx" height="100rpx" :src="getLoadSrc">
						<template v-slot:error>
							<view style="font-size: 24rpx">请上传</view>
						</template>
					</u-image>
				</uni-forms-item>
			</uni-forms>
		</view>
		<!-- 运输中的订单可以修改 卸车榜单 -->
		<view class="centerItem" v-if="[3, 4].includes(+formData.vehicleState)">
			<uni-section type="line" class="mb-10" title="卸车信息">
				<template v-slot:right>
					<text v-if="handStatus.editUnload" @click="close(1)">保存</text>
					<text v-else @click="open(1)">编辑</text>
				</template>
			</uni-section>
			<!-- 卸车信息form -->
			<!-- {{ formData }} -->
			<uni-forms :modelValue="formData">
				<uni-forms-item label-width="180rpx" required label="实卸吨位" name="unloadTonnage">
					<uni-easyinput :disabled="!handStatus.editUnload" type="digit" v-model="formData.unloadTonnage" placeholder="请填写" />
				</uni-forms-item>
				<uni-forms-item label-width="180rpx" required label="卸车榜单" name="bd">
					<u-upload
						v-if="handStatus.editUnload"
						:key="getUnloadList.length + 'unload'"
						width="110"
						height="110"
						ref="rupload"
						:max-count="1"
						:max-size="15 * 1024 * 1024"
						upload-text="上传"
						@on-oversize="() => overSize('卸车榜单')"
						@on-success="(data) => onSuccess(data, 'unload')"
						@on-remove="(idx) => onRemove(idx, 'unload')"
						@on-error="onError"
						@on-choose-complete="onChooseComplete"
						:header="header"
						:file-list="getUnloadList"
						:action="baseFilesURL"
					></u-upload>
					<u-image v-else width="100rpx" height="100rpx" :src="getUnloadSrc">
						<template v-slot:error>
							<view style="font-size: 24rpx">请上传</view>
						</template>
					</u-image>
					<!-- v-if="handStatus.editUnload" -->
				</uni-forms-item>
				<uni-forms-item label-width="180rpx" required name="unloadDate" label="卸车日期">
					<uni-datetime-picker :disabled="!handStatus.editUnload" type="date" v-model="formData.unloadDate" />
				</uni-forms-item>
			</uni-forms>
		</view>

		<!-- 卸车之后 不支持单独提交 -->
		<view v-if="![1].includes(+formData.vehicleState)">
			<u-button type="primary" @click="submit">提交</u-button>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { baseFilesURL, baseFilesVisitURL } from '@/common/request.js';
import { loadingConfirm, unloadAfterEditConfirm, unloadConfirm } from '@/api/drive';
import { navBack, setLoadingToast, setToast } from '@/common/utils';
import { forIn } from 'lodash';
import { getToken } from '@/common/user';

const header = {
	'Cache-Id': getToken()
};

const handStatus = ref({
	editLoading: false, // 装车信息开启编辑
	editUnload: false // 卸车信息开启编辑
});

// key
// // 车辆状态;1未到厂，2已到厂，3已装车，4已卸车
const vehicleStateValue = {
	1: '未到厂',
	2: '已到厂',
	3: '已装车',
	4: '已卸车'
};

// 基本信息
const tableLabel = {
	id: 'ID',
	vehicleNo: '车号',
	// 车辆状态;1未到厂，2已到厂，3已装车，4已卸车
	vehicleState: '车辆状态',
	commodityName: '商品名称',
	companyName: '公司名称',
	loadingDate: '装车日期',
	tonnage: '预装吨位',
	loadingAddress: '装车地点',
	unloadAddress: '卸车地点',
	loadingNotice: '装车注意事项',
	unloadNotice: '卸车注意事项'
};

// 表单信息
const formData = ref({
	id: '',
	vehicleNo: '',
	vehicleState: '',
	commodityName: '',
	companyName: '',
	loadingDate: '',
	tonnage: '',
	loadingAddress: '',
	unloadAddress: '',
	loadingNotice: '',
	unloadNotice: '',
	loadingTonnage: '', // 实际装车吨位
	loadingPoundAffix: [], // 装车榜单
	unloadTonnage: '', // 吨位
	loadingDate: '', // 装车日期
	unloadDate: '', // 卸车日期
	unloadPoundAffix: [] // 卸车榜单
});

// 获取卸车榜单图片
const getUnloadSrc = computed(() => {
	let url: any = '';
	const dep = formData.value.unloadPoundAffix;
	if (dep.length) {
		url = baseFilesVisitURL + dep[0].path;
	}
	return url;
});

// 获取卸车榜单列表
const getUnloadList = computed(() => {
	const dep = formData.value.unloadPoundAffix;
	if (dep.length) {
		dep[0].url = baseFilesVisitURL + dep[0].path;
	}
	return dep;
});

// 获取装车榜单图片
const getLoadSrc = computed(() => {
	let url: any = '';
	const dep = formData.value.loadingPoundAffix;
	if (dep.length) {
		url = baseFilesVisitURL + dep[0].path;
	}
	return url;
});

// 获取装车榜单列表
const getloadList = computed(() => {
	const dep = formData.value.loadingPoundAffix;
	if (dep.length) {
		dep[0].url = baseFilesVisitURL + dep[0].path;
	}
	return dep;
});

const onError = (res: any, type: any) => {
	uni.hideLoading();
	setToast('图片上传失败');
};

const onSuccess = (data: any, type: any) => {
	uni.hideLoading();
	// type == loading  装车
	// type == unload  卸车
	// loadingPoundAffix unloadPoundAffix
	const dep = data.data;
	// 图片添加类型（PC展示需要此类型）
	dep.type = 'image';
	dep.suffix = '.' + dep.suffix;
	if (type == 'loading') {
		formData.value.loadingPoundAffix.push(dep);
	} else {
		formData.value.unloadPoundAffix.push(dep);
	}
	setToast('上传成功');
};

// 移除文件 删除 Forms.value.image
const onRemove = (index: any, type: any) => {
	if (type == 'loading') {
		formData.value.loadingPoundAffix.splice(0, 1);
	} else {
		formData.value.unloadPoundAffix.splice(0, 1);
	}
	setToast('删除成功');
};

const onChooseComplete = () => {
	setLoadingToast('上传中...');
};
// 图片大小超出限制
const overSize = (name) => {
	setToast(`${name}大小超出限制15MB`);
};

//
const descriptionGet = () => {
	let str = '';
	const changeData = {};
	cache.value?.dataChangeMsgs.forEach((notify: any) => {
		const changeMap = JSON.parse(notify.content);
		changeMap.forEach(({ fieldName, newValue }) => {
			switch (fieldName) {
				case '装车地点':
					changeData[fieldName] = `装车地点发生改变，新装车地点为:${newValue}`;
					break;
				case '卸车地点':
					changeData[fieldName] = `卸车地点发生改变，新卸货地址为:${newValue}`;
					break;
				default:
					break;
			}
		});
	});

	for (let key in changeData) {
		str += changeData[key] + '。';
	}

	return str + '确认无误请点击下方`确认通知`确认收到。';
	// 当前车辆卸车地点发生改变，新卸货地址为:河南省郑州市，运价为:780，确认无误请点击下方`确认通知`确认收到。
};

// 给上传的
const submit = () => {
	// console.log('formData ====> ', formData.value);
	// loadingConfirm 装车 2
	// unloadConfirm 卸车 3
	// unloadAfterEditConfirm 编辑卸车和装车 4
	const { id, vehicleState, tonnage, loadingTonnage, loadingPoundAffix, unloadTonnage, loadingDate, unloadDate, unloadPoundAffix }: any = formData.value;
	const Submits = {
		data: {},
		method: (data: any) => {
			return new Promise((resolve) => resolve(data));
		},
		// 是否有错误
		err: []
	};
	// 封装条件检查函数
	const checkRequirements = (requirements) => {
		requirements.forEach(({ condition, errorMessage }) => {
			if (condition) {
				Submits.err.push(errorMessage);
			}
		});
	};

	// 装车
	const loadData = { id, tonnage, loadingTonnage, loadingDate, loadingPoundAffix: JSON.stringify(loadingPoundAffix) };
	const loading = () => {
		checkRequirements([
			{ condition: !loadingTonnage, errorMessage: '请填写实装吨位' },
			{ condition: !loadingPoundAffix.length, errorMessage: '请上传装车榜单' },
			{ condition: !loadingDate, errorMessage: '请选择装车日期' }
		]);
		Submits.data = loadData;
		Submits.method = loadingConfirm;
	};

	// 卸车表单
	const unloadData = { id, tonnage, unloadTonnage, unloadDate, unloadPoundAffix: JSON.stringify(unloadPoundAffix) };
	const unloading = () => {
		checkRequirements([
			{ condition: !unloadTonnage, errorMessage: '请填写实卸吨位' },
			{ condition: !unloadPoundAffix.length, errorMessage: '请上传卸车榜单' },
			{ condition: !unloadDate, errorMessage: '请选择卸车日期' }
		]);
		Submits.data = unloadData;
		Submits.method = unloadConfirm;
	};

	// 当已卸车后，可以编辑
	const allEdit = () => {
		checkRequirements([
			{ condition: !loadingDate, errorMessage: '请选择装车日期' },
			{ condition: !loadingTonnage, errorMessage: '请填写实装吨位' },
			{ condition: !loadingPoundAffix.length, errorMessage: '请上传装车榜单' },
			{ condition: !unloadTonnage, errorMessage: '请填写实卸吨位' },
			{ condition: !unloadPoundAffix.length, errorMessage: '请上传卸车榜单' },
			{ condition: !unloadDate, errorMessage: '请选择卸车日期' }
		]);
		Submits.data = { ...loadData, ...unloadData };
		Submits.method = unloadAfterEditConfirm;
	};

	switch (parseInt(vehicleState)) {
		case 2:
			loading();
			break;
		case 3:
			unloading();
			break;
		case 4:
			// 修改所有的
			allEdit();
			break;
	}

	// 如果有错误
	if (Submits.err.length) {
		return setToast(Submits.err[0]);
	}

	console.log('Submits ====>  ', Submits.data);
	// 执行
	setLoadingToast('提交中...');
	Submits.method(Submits.data).then((res: any) => {
		uni.hideLoading();
		if (res.data !== false) {
			uni.$emit('ok', id);
			navBack();
		}
	});
};

const open = (type: number) => {
	if (type == 0) {
		handStatus.value.editLoading = true;
	} else {
		handStatus.value.editUnload = true;
	}
};

const close = (type: number) => {
	if (type == 0) {
		handStatus.value.editLoading = false;
	} else {
		handStatus.value.editUnload = false;
	}
};

const updateData = (data: any) => {
	const { loadingTonnage = '', loadingPoundAffix, unloadTonnage = '', unloadDate, loadingDate, unloadPoundAffix }: any = data;
	// loadingTonnage: '', // 实际装车吨位
	// loadingPoundAffix: [], // 装车榜单
	// unloadTonnage: '', // 实际卸车吨位
	// unloadDate: '', // 卸车日期
	// unloadPoundAffix: [] ,// 卸车榜单
	const parse = (jsonData: any) => {
		const data = JSON.parse(jsonData || '[]');
		return data.map((v: any) => {
			v.url = baseFilesVisitURL + v.path;
			return v;
		});
	};
	console.log('loadingDate ================> ', loadingDate);
	formData.value = {
		...formData.value,
		// 这里必须要判断一下 因为如果是null, 会导致组件渲染失败
		loadingTonnage: loadingTonnage || '',
		loadingPoundAffix: parse(loadingPoundAffix),
		unloadTonnage: unloadTonnage || '',
		unloadDate,
		loadingDate,
		unloadPoundAffix: parse(unloadPoundAffix)
	};
};

const cache = ref<any>({});
onLoad((options) => {
	const D = JSON.parse(decodeURIComponent(options.item));
	cache.value = D.item;
	// 渲染表格
	forIn(tableLabel, (_, key) => {
		if (tableLabel[key]) {
			formData.value[key] = D.item[key];
		}
	});
	// 渲染装卸车信息
	updateData(D.item);
});
</script>

<style lang="scss" scoped>
$uni-success: #18bc37 !default;

.isId {
	display: none !important;
}

.uni-wrap {
	flex-direction: column;
	/* #ifdef H5 */
	height: calc(100vh - 44px);
	/* #endif */
	/* #ifndef H5 */
	height: 100vh;
	/* #endif */
	flex: 1;
}

.mb-10 {
	margin-bottom: 10px;
}

.decoration {
	width: 6px;
	height: 6px;
	margin-right: 4px;
	border-radius: 50%;
	background-color: $uni-success;
}

.container {
	padding: 30rpx;
	padding-bottom: 150rpx;

	.centerItem {
		.redText {
			color: red;
			padding: 30rpx 0;
		}

		.centerItemBody {
			.centerItemBodyList {
				display: flex;
				font-size: 26rpx;
				.label {
					display: block;
					padding: 10rpx 0;
					width: 200rpx;
					font-weight: 500;
					text-align: right;
					// border: 1rpx solid red;
					border-right: 0;
				}
				.value {
					flex: 1;
					padding: 10rpx;
					// border: 1rpx solid red;
					color: #565656;
				}
			}
		}
	}

	.uploadBox {
		width: 110rpx;
		height: 110rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background: #f4f5f6;

		.bg {
			width: 80rpx;
			height: 80rpx;
		}
	}
}
</style>

<style>
.uni-section-header {
	padding: 12px 10px 0 !important;
}
</style>
